package com.yx.pc.api.controller;

import com.yx.modules.api.annotation.AuthIgnore;
import com.yx.modules.api.entity.TbUser;
import com.yx.modules.api.service.TbUserService;
import com.yx.pay.oauth.AdvancedUtil;
import com.yx.pay.oauth.WeixinOauth2Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 授权后的回调请求处理
 * Created by wuye on 2018/3/5.
 */
@RestController
@RequestMapping("pc/api/oauth")
public class OAuthController {

    @Autowired
    private TbUserService tbUserService;


    @AuthIgnore
    @GetMapping("/auth")
    public ModelAndView doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("==============================进入授权获取=================================");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        // 用户同意授权后，能获取到code
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String[] arr = state.split(",");
        System.out.println("=====================id="+state+"=================================");

        System.out.println("==============================code"+code+"================================");
        String money = arr[1];
        Long userId = Long.valueOf(arr[0]);
        Map<String, Object> map = new HashMap<>();
        //获取用户
        TbUser tbUser = tbUserService.foundById(userId);
        // 用户同意授权
        if (!"authdeny".equals(code)) {
            System.out.println("==============================开始进去获取================================");
            // 获取网页授权access_token
            WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken("wx83e895bd1ea53c4f", "5a681c10ccf1924582bbb2988dd62053", code);
            // 用户标识
            String openId = weixinOauth2Token.getOpenId();
            //用户信息
            tbUser.setOpenid(openId);
            //更新用户信息
            tbUserService.update(tbUser);
          // 设置要传递的参数
          request.setAttribute("money", money);
        }
//        return R.ok().put("data",user);
        // 跳转到index.jsp
//         request.getRequestDispatcher("www.guangtouboy.com").forward(request, response);
//        ModelAndView view = new ModelAndView("redirect:http://www.guangtouboy.com/#/Login?token=" + map.get("token").toString());
//        view.addObject("state",state);
//        return view;
        return new ModelAndView("redirect:http://www.youwenyuedu.com:8082/#/checkMoneyWx?money="+money);
    }
}
